<?php

namespace addons\qingdong\controller;


use addons\qingdong\model\Contacts;
use addons\qingdong\model\Contract;
use addons\qingdong\model\Customer;
use addons\qingdong\model\Flow;
use addons\qingdong\model\Leads;
use addons\qingdong\model\Receivables;
use addons\qingdong\model\Remind;
use addons\qingdong\model\Staff as StaffModel;
use addons\qingdong\model\StaffDepartment;
use addons\qingdong\library\Wechat;
use addons\qingdong\model\Achievement;
use addons\qingdong\model\Record;
use fast\Http;
use think\Exception;
use think\Log;
use think\Validate;

/**
 *  * 操作文档：https://doc.fastadmin.net/qingdong
 * 软件介绍：https://www.fastadmin.net/store/qingdong.html
 * 售后微信：qingdong_crm
 * 员工登录 注册接口
 */
class Staff extends StaffApi
{
    protected $noNeedLogin = ['test', 'wxLogin', 'login','logintest'];
    protected $noNeedRight = ['getInfo', 'editInfo', "use_phone"];


    public function _initialize()
    {
        parent::_initialize();
    }

    //是否登录
    public function isLogin()
    {
        $this->success('已登录', ['userinfo' => $this->auth->getUserinfo()]);
    }



    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account 账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    //获取个人基本信息
    public function getInfo()
    {
        $staff = StaffModel::where(['id' => $this->auth->id])->with(['department', 'parent'])->find();
        $group_ids=explode(',',$staff['group_ids']);
        $staff['role_type'] = 1;//基础和团队
        if (in_array(1, $group_ids)) {//超级管理员
            $staff['role_type'] = 9;
        }
        $this->success('请求成功', $staff);
    }

    //员工绑定信息
    public function staffBind(){
        $staff=StaffModel::get($this->auth->id);
        $data=[
            'is_bind_wechat'=>$staff['openid']?1:($staff['wx_openid']?1:0)
        ];
        $this->success('请求成功',$data);
    }

    //绑定微信
    public function wechatBind(){
        $type=input('type');//applet小程序   web 网页授权
        $code = input('code');
        if($type == 'web'){
            $wechat = new Wechat('wxOfficialAccount');
            if(empty($wechat->config['app_id'])){
                $this->error('微信公众号appid未设置');
            }
            if(empty($wechat->config['secret'])){
                $this->error('微信公众号secret未设置');
            }
            $decryptSession = $wechat->getOfficialAccessToken($code);

            if (isset($decryptSession['errcode']) && $decryptSession['errcode'] != 0) {
                $this->error(__('解析失败！'));
            }
            $openid = $decryptSession['openid'];
            $unionid = $decryptSession['unionid'] ?? '';

            Log::info(json_encode($decryptSession,JSON_UNESCAPED_UNICODE));
            //判断用户是否存在
            $staff = StaffModel::where(['wx_openid' => $openid])->find();
            if($staff){
                $this->error('该微信号已绑定账号');
            }
            $staffModel=new StaffModel();
            $result=$staffModel->save(['wx_openid'=>$openid,'unionid'=>$unionid],['id'=>$this->auth->id]);
            if($result){
                $this->success('绑定成功');
            }
            $this->error('绑定失败');
        }elseif($type == 'applet'){
            $wechat = new Wechat('wxMiniProgram');
            if(empty($wechat->config['app_id'])){
                $this->error('微信小程序appid未设置');
            }
            if(empty($wechat->config['secret'])){
                $this->error('微信小程序secret未设置');
            }
            $decryptSession = $wechat->code($code);

            if (isset($decryptSession['errcode']) && $decryptSession['errcode'] != 0) {
                $this->error(__('解析失败！'));
            }
            $openid = $decryptSession['openid'];
            $unionid = $decryptSession['unionid'] ?? '';
            //判断用户是否存在
            $staff = StaffModel::where(['openid' => $openid])->find();
            if($staff){
                $this->error('该微信号已绑定账号');
            }
            $staffModel=new StaffModel();
            $result=$staffModel->save(['openid'=>$openid,'unionid'=>$unionid],['id'=>$this->auth->id]);
            if($result){
                $this->success('绑定成功');
            }
            $this->error('绑定失败');
        }
    }

    //解绑微信
    public function unboundWechat()
    {
        $staffId = $this->auth->id;
        $model = new StaffModel();
        $staff = $model->where(['id' => $staffId])->find();
        if (empty($staff)) {
            $this->error('员工不存在');
        }
        if ($model->isUpdate(true)->save(['id' => $staffId, 'wx_openid' => null,
            'unionid' => null, 'openid' => null])) {
            $this->success('解绑微信成功');
        }
        $this->error('操作失败');
    }
    //修改个人基本信息
    public function editInfo()
    {
        $name = input('name');
        $img = input('img');
        $email = input('email');
        $sex = input('sex');
        $num = input('num');
        $post = input('post');
        $mobile = input('mobile');
        $staffs = StaffModel::where(array('id' => $this->auth->id))->find();
        $staffs->mobile = $mobile;
        $staffs->img = $img;
        $staffs->email = $email;
        $staffs->sex = $sex;
        $staffs->num = $num;
        $staffs->post = $post;
        $staffs->updatetime = time();
        $result = $staffs->save();
        if (!$result) {
            $this->error('修改失败');
        }
        $this->success('修改成功');
    }


    //授权手机号
    public function use_phone()
    {
        $code = $this->request->post('code','',null);
        $encryptedData = $this->request->post('encryptedData','',null);
        $iv = $this->request->post('iv','',null);
        $config = new Wechat('wxMiniProgram');
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $config->config['app_id'] . "&secret=" . $config->config['secret'] . "&js_code=" . $code . "&grant_type=authorization_code";
        $user = curl_getinfo($url);
        $arr = json_decode($user, true);
        if (isset($arr['errcode']) && $arr['errcode'] != 0) {
            $this->error('操作失败！');
        }
        if (!isset($arr['openid']) || !isset($arr['session_key'])) {
            $this->error('授权失败,请重新授权！');
        }
        $openId = $arr['openid'];
        $pc = new Wxbizdatacrypt($config->config['app_id'], $arr['session_key']);
        $errCode = $pc->decryptData($encryptedData, $iv, $data);
        if ($errCode != 0) {
            $this->error('授权失败,请重新授权！');
        }
        $decryptUserInfo = json_decode($data, true);
        if (isset($decryptUserInfo['phoneNumber']) && !empty($decryptUserInfo['phoneNumber'])) {
            $user_id = $this->auth->id;
            $userInfo = StaffModel::where(array('id' => $user_id))->update(array('mobile' => $decryptUserInfo['phoneNumber']));
            if ($userInfo === false) {
                $this->error('绑定失败！');
            }
            $data = ['mobile' => $decryptUserInfo['phoneNumber']];
            $this->success('绑定成功', $data);
        } else {
            $this->error('授权失败！');
        }
    }


    //获取下级员工列表
    public function getStaffList()
    {
        $ids = StaffModel::getLowerStaffId();
        $staff = StaffModel::where([
            'id' => ['in', $ids],
            'status' => 1
        ])->with(['parent'])->field('id,name,nickname,img,num,mobile,post,parent_id')->select();
        $this->success('请求成功', $staff);
    }


    //获取员工详情
    public function getStaffDetail()
    {
        $id = input('id');
        if (empty($id)) {
            $this->error('员工不存在');
        }
        $staff = StaffModel::with(['department', 'parent'])->where([
            'id' => $id,
        ])->find();
        $this->success('请求成功', $staff);
    }


    //待审核员工列表
    public function getCheckStaffList()
    {
        $staff = StaffModel::where([
            'status' => 0,
            'name' => ['neq', '']
        ])->field('id,name,nickname,img,num,mobile,post,status')->select();
        $this->success('请求成功', $staff);
    }

    //修改员工信息
    public function updateStaff()
    {
        $name = input('name', '');
        $img = input('img', '');
        $email = input('email', '');
        $sex = input('sex', 0);
        $num = input('num', '');
        $post = input('post', '');
        $parent_id = input('parent_id', 0);
        $id = input('id', 0, 'intval');
        if (StaffModel::where(['id' => $id])->update([
                'name' => $name,
                'img' => $img,
                'email' => $email,
                'sex' => $sex,
                'num' => $num,
                'post' => $post,
                'parent_id' => $parent_id,
                'updatetime' => time()
            ]) == false) {
            $this->error('修改失败');
        }
        $this->success('修改成功');
    }

    //审核员工成功
    public function checkStaffSuccess()
    {
        $name = input('name', '');
        $img = input('img', '');
        $email = input('email', '');
        $sex = input('sex', 0);
        $role = input('role', 0);
        $num = input('num', '');
        $post = input('post', '');
        $mobile = input('mobile', '');
        $department_id = input('department_id', 0);
        $parent_id = input('parent_id', 0);
        $id = input('id', 0, 'intval');
        if (StaffModel::where(['id' => $id, 'status' => 0])->find() == false) {
            $this->error('待审核员工不存在');
        }
        if (empty($department_id)) {
            $this->error('请选择员工部门！');
        }
        if (StaffModel::where(['id' => $id])->update([
                'name' => $name,
                'img' => $img,
                'email' => $email,
                'sex' => $sex,
                'num' => $num,
                'role' => $role,
                'mobile' => $mobile,
                'post' => $post,
                'parent_id' => $parent_id,
                'department_id' => $department_id,
                'status' => 1,
                'updatetime' => time()
            ]) == false) {
            $this->error('审核失败');
        }
        $this->success('审核成功');
    }

    //审核员工拒绝
    public function checkStaffError(){
        $id = input('id');
        if (StaffModel::where(['id' => $id, 'status' => 0])->find() == false) {
            $this->error('待审核员工不存在');
        }
        if (StaffModel::where(['id' => $id, 'status' => 0])->update(['deletetime' => time()]) == false) {
            $this->error('拒绝失败');
        }
        $this->success('审核成功');
    }

    //获取员工统计
    public function getStaffStatistics()
    {
        $id = input('id');
        if (empty($id)) {
            $this->error('员工不存在');
        }
        $date = input('date', date('Y-m'));
        //月底
        $endDate = strtotime('+1 month', strtotime(date($date . '-1')));
        $date = strtotime($date);
        //客户 线索 联系人 合同 回款 跟进次数 处理审批
        $leads = Leads::where([
            'create_staff_id' => $id,
            'createtime' => ['between', [$date, $endDate]],
        ])->count();
        $customer = Customer::where([
            'create_staff_id' => $id,
            'createtime' => ['between', [$date, $endDate]],
        ])->count();
        $contacts = Contacts::where([
            'create_staff_id' => $id,
            'createtime' => ['between', [$date, $endDate]],
        ])->count();
        $contract = Contract::where([
            'create_staff_id' => $id,
            'createtime' => ['between', [$date, $endDate]],
            'check_status' => 2
        ])->count();
        $contract_money = Contract::where([
            'create_staff_id' => $id,
            'createtime' => ['between', [$date, $endDate]],
            'check_status' => 2
        ])->sum('money');
        $receivables = Receivables::where([
            'create_staff_id' => $id,
            'createtime' => ['between', [$date, $endDate]],
            'check_status' => 2
        ])->count();
        $receivables_money = Receivables::where([
            'create_staff_id' => $id,
            'createtime' => ['between', [$date, $endDate]],
            'check_status' => 2
        ])->sum('money');
        $record = Record::where([
            'create_staff_id' => $id,
            'createtime' => ['between', [$date, $endDate]],
        ])->count();

        $field = Achievement::getMonthField(date('Y-m', $date));
        $contractAchievement = Achievement::where([
            'year' => date('Y', $date),
            'type' => 3,
            'obj_id' => $id,
            'status' => 1
        ])->value($field);

        $receivablesAchievement = Achievement::where([
            'year' => date('Y', $date),
            'type' => 3,
            'obj_id' => $id,
            'status' => 2
        ])->value($field);

        $this->success('请求成功', [
            'leads' => $leads,
            'customer' => $customer,
            'contacts' => $contacts,
            'contract' => $contract,
            'contract_money' => $contract_money,
            'receivables' => $receivables,
            'receivables_money' => $receivables_money,
            'record' => $record,
            'contractAchievement' => $contractAchievement ?: 0,
            'receivablesAchievement' => $receivablesAchievement ?: 0,
        ]);
    }

    //获取员工所属客户
    public function getStaffCustomer()
    {
        $id = input('id');
        $limit = input("limit/d", 10);
        $row = StaffModel::get($id);
        if (empty($row)) {
            $this->error('员工不存在');
        }
        $where = [];
        $where['owner_staff_id'] = $id;
        $list = Customer::where($where)->with([
            'ownerStaff',
            'contacts'
        ])->field('id,name,next_time,owner_staff_id,level,follow')->order('id desc')->paginate($limit);

        $this->success('请求成功', $list);
    }

    //获取部门列表
    public function getDepartment()
    {

        $this->success('请求成功', StaffDepartment::getDepartmentList());
    }

    //获取上级列表
    public function getParentList()
    {
        $id = input('id');
        if (empty($id)) {
            $this->error('参数错误');
        }
        $this->success('请求成功', StaffModel::getList([$id]));
    }


    /**
     * 获取用户上级IDs
     */
    public function getStaffIds()
    {
        // record 跟进  contract 合同  consume 费用  receivables 回款
        $type = input('type');
        $remind=Remind::where(['type'=>$type])->find();
        if($remind){
            $staff = StaffModel::where(['id' => ['in', $remind['staff_ids']]])->field('id,name,img')->select();
            $this->success('请求成功', $staff);
        }
        $pid = StaffModel::where(['id' => $this->auth->id])->value('parent_id');
        $pids = [$pid];
        $staff = StaffModel::where(['id' => ['in', $pids]])->field('id,name,img')->select();
        $this->success('请求成功', $staff);
    }

    /**
     * 获取审批列表
     */
    public function getsteplist()
    {
        // record 跟进  contract 合同  consume 费用  receivables 回款 formapproval_1 审批
        $type = input('type');

        //获取审批
        $data = Flow::getsteplist($type);
        if (empty($data)) {
            $this->error('无可用审批流，请联系管理员');
        }
        $this->success('请求成功', $data);
    }
    /**
     * 获取审批详情
     */
    public function getstepdetail()
    {
        // record 跟进  contract 合同  consume 费用  receivables 回款
        $type = input('type');
        $relation_id=input('relation_id');
        $data = Flow::getstepdetail($type,$relation_id);
        if (empty($data)) {
            $this->error('无可用审批流，请联系管理员');
        }
        $this->success('请求成功', $data);
    }


    //禁用账号
    public function disable_user()
    {
        $id = input('id');
        $status = 2;
        $model = new StaffModel();
        $staff = $model->where(['id' => $id])->find();
        if (empty($staff)) {
            $this->error('员工不存在');
        }
        if ($model->isUpdate(true)->save(['id' => $id, 'status' => $status])) {
            $this->success('操作成功');
        }
        $this->error('操作失败');
    }
    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }
    /**
     * 修改密码
     */
    public function changepwd()
    {
        if ($this->request->isPost()) {
            $oldpassword = $this->request->post("oldpassword");
            $newpassword = $this->request->post("newpassword");
            $renewpassword = $this->request->post("renewpassword");
            $rule = [
                'oldpassword'   => 'require|length:6,30',
                'newpassword'   => 'require|length:6,30',
                'renewpassword' => 'require|length:6,30|confirm:newpassword',
            ];

            $msg = [
                'renewpassword.confirm' =>'两次输入的密码不一致'
            ];
            $data = [
                'oldpassword'   => $oldpassword,
                'newpassword'   => $newpassword,
                'renewpassword' => $renewpassword,
            ];
            $field = [
                'oldpassword'   => '旧密码',
                'newpassword'   => '新密码',
                'renewpassword' => '确认密码'
            ];
            $validate = new Validate($rule, $msg, $field);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()));
                return false;
            }

            $ret = $this->auth->changepwd($newpassword, $oldpassword);
            if ($ret) {
                $this->success('修改密码成功');
            } else {
                $this->error($this->auth->getError());
            }
        }
    }
    //直接体验
    public function logintest()
    {
        $staff = StaffModel::where([])->order('id asc')->find();
        if(!$staff){
            $this->error('员工不存在');
        }
        $stafflogin= $this->auth->direct($staff['id']);
        if ($stafflogin) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error('登录失败');
        }

    }

}
